import datetime
from flask import current_app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy import Column, ForeignKey, func
from sqlalchemy import String, Unicode, DateTime, Boolean
from sqlalchemy import SmallInteger, Integer, TIMESTAMP
from sqlalchemy.orm import relationship
from app.models.base import db, Base
from app import login_manager


class User(UserMixin, Base):
    __tablename__ = 'students'

    id = Column("student_id", Integer, primary_key=True)
    nickname = Column("nick_name", String(255), default=None, nullable=False)
    tel = Column("phonenum", String(20  ), nullable=False,default=None, )
    userid = Column("username", String(255), nullable=False)
    avatar_url = Column("avatar_url", String(255), nullable=False,default=None)
    # password = Column("password", String(255),  nullable=False)
    confirmed = Column("verify_state", SmallInteger,nullable=False, default=0)
    beans = Column("study_pee", Integer, nullable=False,default=0)
    gender = Column("gender", SmallInteger,nullable=False, )
    _password = Column("password", String(255), nullable=False)
    created_at = Column("created_at", TIMESTAMP, default=datetime.datetime.now(),nullable=False,)
    updated_at = Column("updated_at", TIMESTAMP, default=datetime.datetime.now(), nullable=False,)
    imagefile = relationship('ImageFile')
    # def __init__(self, nickname, email, password, phone_number=None):
    #     self.nickname = nickname
    #     self._password = generate_password_hash(password)
    #     self.email = email
    #     self.phone_number = phone_number
    #     super(User, self).__init__()

    @property
    def pwd(self):
        return self._password

    @pwd.setter
    def pwd(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def generate_token(self, expiration=600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'id': self.id}).decode('utf-8')



    @staticmethod
    def reset_password(token, new_password):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        user = User.query.get(data.get('id'))
        if user is None:
            return False
        user.password = new_password
        db.session.commit()
        return True

    # @property
    # def summary(self):
    #     return dict(
    #         nickname=self.nickname,
    #         beans=self.beans,
    #         email=self.email,
    #         send_receive=str(self.send_counter) + '/' + str(self.receive_counter)
    #     )


@login_manager.user_loader
def get_user(uid):
    return User.query.get(int(uid))
